package fr.appliClient.client.widget.Main;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Hyperlink;
import com.google.gwt.user.client.ui.Widget;

import fr.appliClient.client.i18n.Messages;
import fr.appliClient.client.widget.View;

public class MainView extends View<MainPresenterCallBack> implements MainDisplay {

	private static MainUiBinder uiBinder = GWT.create(MainUiBinder.class);

	private Messages messages = GWT.create(Messages.class);

	interface MainUiBinder extends UiBinder<Widget, MainView> {
	}

	private String label = "null";

	@UiField
	HTMLPanel centerHtml;

	@UiField
	HorizontalPanel headerPanel;

	public MainView() {

		initWidget(uiBinder.createAndBindUi(this));
		initHeader();
		init();
	}

	private void initHeader() {

		Hyperlink headerHomeHyperlink = new Hyperlink(messages.headerValue(), "home");
		this.headerPanel.add(headerHomeHyperlink);
	}

	public void init() {

		this.centerHtml.clear();
		RequestBuilder builder = new RequestBuilder(RequestBuilder.GET,
				"http://localhost:8080/Appliclient.webService/vehicle/test");
		builder.setHeader("content-type", "application/json");

		try {
			Request responce = builder.sendRequest("test?", new RequestCallback() {

				@Override
				public void onResponseReceived(Request request, Response response) {

					int statusCode = response.getStatusCode();

					if (statusCode == Response.SC_OK) {
						String responseBody = response.getText();
						label = responseBody;
						System.out.println(responseBody);
					} else {
						label = "fail !!";
						System.out.println("FAIL!!!!");
					}

				}

				@Override
				public void onError(Request request, Throwable exception) {

					// TODO Auto-generated method stub

				}
			});
		} catch (RequestException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		Button mainTableButton = new Button(label);
		mainTableButton.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {

				History.newItem("main");

			}
		});

		this.centerHtml.add(mainTableButton);
	}

	@Override
	public Widget asWidget() {

		return this;
	}

	public HasWidgets getCenter() {

		return centerHtml;
	}
}
